import React from 'react'
import '@babel/polyfill'
import '../styles/index.less'
import { initStore } from '../model/store'
import withRematch from '../utils/withRematch'
import { withRouter } from 'next/router'
import Head from 'next/head'
import { Button } from 'antd'
import 'isomorphic-unfetch'
import { goodslistMix } from '../api/index'
import Example from '../components/testhooks'

class Index extends React.Component {
  static async getInitialProps({ query, req, res }) {
    let hostName = null
    if (!req) {
      hostName = window.location.host
    } else {
      hostName = req.headers.host
    }

    let goodsListData = {}
    let indexErr = null
    try {
      if (query) {
        let arr = []
        if (JSON.stringify(query) === '{}') {
          arr = ['pageIndex=1', 'pageSize=20', 'businessNo=xubei']
        } else if (query.pageIndex === undefined) {
          arr = ['pageIndex=1', 'pageSize=20', 'businessNo=xubei']
        } else {
          arr = ['pageSize=20', 'businessNo=xubei']
        }
        if (query && query.gameid) {
          query.gameId = query.gameid
          delete query.gameid
        }
        for (let i in query) {
          if (query[i]) {
            arr.push(`${i}=${encodeURI(query[i])}`)
          }
        }
        const productListRes = await fetch(goodslistMix + '?' + arr.join('&'), {
          credentials: 'include',
        })
        const productlistResult = await productListRes.json()
        if (productlistResult.code === '1') {
          goodsListData = productlistResult.result
        } else if (productlistResult.code === 430) {
          goodsListData = {}
        }
      }
    } catch (err) {
      console.log('服务端请求报错', err)
      indexErr = err
    }
    return { goodsListData, indexErr }
  }

  state = {
    page: 'index',
  }

  componentDidMount() {
    const { router, dispatch, hostName, curentPage } = this.props
    const { query, pathname } = router
  }

  render() {
    const { dispatch, router, goodsListData, indexErr, name } = this.props
    if (indexErr) {
      console.log(indexErr, '服务端接口请求报错！')
    } else {
      console.log('goodsListData', goodsListData)
    }

    return (
      <div className='next_template'>
        <Head>
          <title>next_template</title>
          <meta name='renderer' content='webkit' />
          {/* <link rel='icon' href={returnIconByDomain(hostName)} /> */}
          {/* 接入听云 */}
          <script src='/static/tingyun-rum.js'></script>
        </Head>
        <div>{name}</div>
        <Button type='primary'>测试</Button>
        <Example />
      </div>
    )
  }
}

export default withRematch(initStore, (state) => ({
  ...state.indexModel,
}))(withRouter(Index))
